import { Component, OnInit } from '@angular/core';
import { AlertController } from '@ionic/angular';
import { ActivatedRoute } from '@angular/router';
import { ApiService } from '../api/api.service';
import { SearchVO } from '../vo/SearchVO';
import { ApiUrl } from '../api/ApiUrl';
import { ApiRequest } from '../api/ApiRequest';
import { Router } from '@angular/router';
@Component({
  selector: 'app-search',
  templateUrl: './search.page.html',
  styleUrls: ['./search.page.scss'],
})
export class SearchPage extends ApiRequest implements OnInit {

  queryText = '';
  items: SearchVO[] = [];
  start: number;
  constructor( private router: Router,
    public api: ApiService, public activatedRoute: ActivatedRoute, public alertController: AlertController) {
    super();
  }

  ngOnInit() {
    this.queryText = this.activatedRoute.snapshot.paramMap.get('queryText');
    this.doDownRefresh(null);
  }

  onQueryBtnClick() {
    this.items.length = 0;
    this.doDownRefresh(null);
  }
  // 下拉刷型界面
  doDownRefresh(evt) {
    this.start = 1;
    this.onSearch(this.queryText, evt);
  }

  onSearch(queryText: string, evt: any, opt: string = 'up') {
    if (queryText === '' || queryText === null) {
      if (evt) {
        evt.target.complete();
      }
      this.showAlert();
      return;
    }
    this.api.getItems<SearchVO>(ApiUrl.searchQuery, { 'tvalue': queryText, 'start': this.start }).subscribe(response => {
      if (evt) {
        evt.target.complete();
      }
      if (response === null || response.length === 0) {
        console.log('没有数据返回');
        return;
      } else {
        this.start += 1;
      }
      console.log(opt);
      console.log(response);
      if (opt === 'up') { // 把新的数据追加到list的尾部
        this.items = this.items.concat(response);
      }
    }, () => {
      if (evt) {
        evt.target.complete();
      }
      console.log('出错了');
    });
  }

  doUpRefresh(evt) {
     console.log('上拉刷新');
      this.onSearch(this.queryText, evt, 'up');
  }

  // 提示
  async showAlert() {
    const alert = await this.alertController.create({
      header: '提示',
      message: '请输入查询内容！',
      buttons: ['确定']
    });

    await alert.present();
  }

  goToDetails(tid, tname) {
   if (tname === 'bank') {
    this.router.navigate(['/bankdetails', { 'iid': tid }]);
   }
   if (tname === 'article') {
    this.router.navigate(['/article', { 'iid': tid }]);
   }
   if (tname === 'video') {
    this.router.navigate(['/video', { 'iid': tid }]);
   }
   if (tname === 'company') {
    this.router.navigate(['/companydetail', {'iid': tid}]);
   }
   if (tname === 'consultant') {
    this.router.navigate(['/guwendetails', {'iid': tid}]);
   }
  }

}
